<template>
  <!-- !房东信息 -->
  <div class="room-proprietor beauty-scroller-bar">
    <template v-if="hasProprietor">
      <CustomTable
        ref="customTableRef"
        :requestInfo="{
          service: '/village', // 请求服务
          serviceUrl: '/project/room/getOwnerListByRoom', // 请求url
          serviceType: 'get', // 请求方式
        }"
        :hasPagination="false"
        :extraParams="extraParams"
        :hasMoreAction="false"
        :columns="columns"
        titleRowAlign="bottom"
        :tableConfig="$store.getters.tableConfig"
        @request="$utils.commonRequest"
      >
        <template #leftTitle>
          <a-form layout="vertical">
            <a-row :gutter="12">
              <a-col :span="6">
                <a-form-item label="业户类型">
                  <a-select
                    class="w-100p"
                    :allowClear="true"
                    placeholder="请选择业户类型"
                    v-model:value="searchParams.type"
                    :options="typeOptions"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="业户名称">
                  <TenantComponent
                    :ownerId="searchParams.owner_id"
                    titleser="选择业户"
                    @selectcancel="handleSelectOwner"
                    @request="$utils.commonRequest"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="合同编号">
                  <a-input
                    placeHolder="搜索合同编号"
                    v-model:value="searchParams.contract_number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label=" ">
                  <a-space>
                    <a-button type="primary" @click="handleSearchData">搜索</a-button>
                    <a-button @click="resetData">重置</a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </template>
        <template #column-owner_name="{ record, text }">
          <span :class="record.owner_id ? 'link' : ''" @click="toOwnerDetail(record.owner_id)">
            {{ text }}
          </span>
          <a-tag style="margin-left: 4px" v-if="record.is_current == 1" color="blue">{{`当前${record.type}`}}</a-tag>
        </template>
        <template #column-contract_number="{ record, text }">
          <span v-if="record.id" class="link" @click="toContractDetail(record.id)">
            {{ text }}
          </span>
          <span v-else>--</span>
        </template>
      </CustomTable>
    </template>
    <div class="no-proprietor" v-else>
      <a-empty description="当前房源未绑定房东" />
      <a-button type="primary" @click="newContract">录入成本合同</a-button>
    </div>


    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="
        () => {
          ownerDetailVisible = false;
        }
      "
    />

    <!--  合同详情  -->
    <ContractDetailDrawer
      :visible="contractDetailVisible"
      :id="contractDetailId"
      @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
      @closeAllModal="closeAllModal"
    />
  </div>
</template>
<script>
import {computed, defineAsyncComponent, defineComponent, reactive, toRefs} from "vue";
import { DownOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter } from "vue-router";
import { CustomTable, TenantComponent } from "bl-common-vue3";
import {Form} from "ant-design-vue";
const OwnerDetailDrawer = defineAsyncComponent(() =>
  import("@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue")
);
const ContractDetailDrawer = defineAsyncComponent(() =>
  import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);
const useForm = Form.useForm;
import _ from "lodash";
export default defineComponent({
  name: "RoomProprietor",
  props: {
    detail: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    DownOutlined,
    CustomTable,
    OwnerDetailDrawer,
    ContractDetailDrawer,
    TenantComponent,
  },
  setup(props, { emit }) {
    const ROUTER = useRouter();

    const state = reactive({
      hasProprietor: true,
      tableSearchParams: {},
      ownerId: 0,
      ownerDetailVisible: false,
      contractDetailId: 0,
      contractDetailVisible: false,
      customTableRef: null,
    });

    const extraParams = computed(() => {
      return {
        ...state.tableSearchParams,
        build_id: props.detail.build_id,
        room_id: props.detail.id,
      }
    });

    const searchParams = reactive({
      type: undefined,
      owner_id: undefined,
      contract_number: '',
    });

    const {resetFields} = useForm(searchParams, {});

    const newContract = () => {
      emit("close");
      if (window.__MICRO_APP_ENVIRONMENT__) {
        let microAppUrl = `/contract/addContract?room_id=${props.detail.id}&village_id=${props.detail.village_id}&layer_id=${props.detail.layer_id}&build_id=${props.detail.build_id}&contractType=costContract`
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_add_contract_${props.detail.id}_${props.detail.village_id}_${props.detail.layer_id}_${props.detail.build_id}_costContract`,
            app: 'org',
            name: `创建合同`,
            url: microAppUrl,
          }
        })
      }
    };

    const toOwnerDetail = (id) => {
      if (!id) return;
      state.ownerId = id;
      state.ownerDetailVisible = true;
    };

    const toContractDetail = (id) => {
      if (!id) return;
      state.contractDetailId = id;
      state.contractDetailVisible = true;
    };

    const handleSearchData = () => {
      state.tableSearchParams = _.cloneDeep(searchParams);
      state.customTableRef?.loadData(true);
    };

    const resetData = () => {
      resetFields();
      state.tableSearchParams = _.cloneDeep(searchParams);
      state.customTableRef?.loadData(true);
    };

    const getList = () => {
      request.get("/village", '/project/room/getOwnerListByRoom', {
        build_id: props.detail.build_id,
        room_id: props.detail.id,
      }).then((res) => {
        state.hasProprietor = res?.list?.length > 0;
      })
    };

    const handleSelectOwner = (id) => {
      searchParams.owner_id = id;
    };

    const init = () => {
      getList();
    };

    init();

    const closeAllModal = () => {
      emit("close");
    };

    return {
      columns,
      searchParams,
      typeOptions,
      ...toRefs(state),
      extraParams,
      toOwnerDetail,
      toContractDetail,
      newContract,
      closeAllModal,
      handleSearchData,
      resetData,
      handleSelectOwner,
    };
  },
});

const columns = [
  {
    title: "业户类型",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "业户名称",
    dataIndex: "owner_name",
    key: "owner_name",
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number",
  },
  {
    title: "合同起始时间",
    dataIndex: "lease_starttime",
    key: "lease_starttime",
    customRender: ({text}) => {
      return text || "--";
    },
  },
  {
    title: "合同终止时间",
    dataIndex: "lease_endtime",
    key: "lease_endtime",
    customRender: ({text}) => {
      return text || "--";
    },
  },
];

const typeOptions = [
  {
    value: 1,
    label: '业主',
  },
  {
    value: 2,
    label: '租客',
  },
];
</script>

<style lang="less" scoped>
.room-proprietor {
  width: 100%;
  height: 100%;
  overflow: hidden auto;
  background: #fff;
}
.no-proprietor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.proprietor-name {
  font-size: 15px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.65);
  display: flex;
  align-items: center;
}
:deep(.ant-form-item) {
  margin: 0 !important;
}
</style>
